//
//  ReviewOfTheOrderViewController.m
//  OrderAssistant
//
//  Created by chendong on 2020/10/28.
//  Copyright © 2020 chendong. All rights reserved.
//

#import "ReviewOfTheOrderViewController.h"
#import "ReviewOfTheOrderTableViewCell.h"
#import "ReviewOfTheOrderTableViewCellFrame.h"
#import "ReviewOrderDetailsViewController.h"
#import "NetTools.h"
#import <SVProgressHUD.h>
#import "SummaryOfUnauditedOrdersViewController.h"
#import "FCUUID.h"
#import <AFNetworking.h>
@interface ReviewOfTheOrderViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong) UITableView *myTableView;
@property(nonatomic,strong) NSMutableArray *myTableViewArr;
@property(nonatomic,strong) NSMutableArray *dataDDIC;
@property(nonatomic,strong) NSDictionary *dataDic;
@property(nonatomic,strong) ReviewOfTheOrderTableViewCell *dataDicCell;
@property(nonatomic,strong) NSIndexPath *dataDicCellIndexPath;
@property(nonatomic,strong) NSIndexPath *lastcellPath;
@property(nonatomic,strong) UIView *noView;
@property(nonatomic,strong) UIView *bottomBGV;

@end

@implementation ReviewOfTheOrderViewController
-(UIView *)noView{
    if (!_noView) {
        _noView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT)];
        _noView.backgroundColor = RGBCOLOR(230, 230, 230);
        [self.view addSubview:_noView];
        UIImageView *noIMGv = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 115, 115)];
        noIMGv.center = CGPointMake(_noView.frame.size.width/2, _noView.frame.size.height/2);
        noIMGv.image = [UIImage imageNamed:@"icon_empty.png"];
        [_noView addSubview:noIMGv];
        UILabel *lllll = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(noIMGv.frame), SCREENWIDTH, 50)];
        lllll.text = @"空空如也";
        lllll.textAlignment = NSTextAlignmentCenter;
        lllll.textColor = RGBCOLOR(181, 181, 181);
        [_noView addSubview:lllll];
    }
    return _noView;
}
-(NSMutableArray *)dataDDIC{
    if (!_dataDDIC) {
        _dataDDIC = [[NSMutableArray alloc]init];
    }
    return _dataDDIC;
}
-(NSMutableArray *)myTableViewArr{
    if (!_myTableViewArr) {
        _myTableViewArr = [[NSMutableArray alloc]init];
    }
    return _myTableViewArr;
}
-(UITableView *)myTableView{
    if (!_myTableView) {
        _myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT-kTabBarHeight-20) style:UITableViewStylePlain];
        _myTableView.dataSource = self;
        _myTableView.delegate = self;
        _myTableView.separatorStyle = UITableViewCellSelectionStyleNone;
//        _myTableView.backgroundColor = [UIColor blueColor];
        [self.view addSubview:_myTableView];
    }
    return _myTableView;
}
#pragma mark <UITableViewDelegate,UITableViewDataSource>
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.myTableViewArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *idf = @"OrderHistoryTableViewCell";
    ReviewOfTheOrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:idf];
    if (!cell) {
        cell = [[ReviewOfTheOrderTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:idf];
    }
    cell.dic = self.myTableViewArr[indexPath.row];
    cell.bgV.backgroundColor = [UIColor whiteColor];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ReviewOfTheOrderTableViewCell *lastcell = [tableView cellForRowAtIndexPath:self.lastcellPath];
    lastcell.bgV.backgroundColor = [UIColor whiteColor];
    self.lastcellPath = indexPath;
    ReviewOfTheOrderTableViewCell *c = [tableView cellForRowAtIndexPath:indexPath];
    c.bgV.backgroundColor = RGBACOLOR(108, 185, 252, 0.3);
    self.dataDicCell = c;
    ReviewOfTheOrderTableViewCellFrame *cccc = self.myTableViewArr[indexPath.row];
    self.dataDic = cccc.dic;
    self.dataDicCellIndexPath = indexPath;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ReviewOfTheOrderTableViewCellFrame *f = self.myTableViewArr[indexPath.row];
    return f.cellH;
//    return 135;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.title = @"审核订单";
    
    UIView *leftV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    UIButton *gwcBtnl = [UIButton buttonWithType:UIButtonTypeCustom];
    gwcBtnl.frame = CGRectMake(0, 5, 30, 30);
    gwcBtnl.userInteractionEnabled = NO;
    [gwcBtnl setImage:[UIImage imageNamed:@"货框_03.png"] forState:UIControlStateNormal];
    gwcBtnl.imageView.contentMode = UIViewContentModeScaleAspectFit;
    UITapGestureRecognizer *t = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(leftAction:)];
    [leftV addGestureRecognizer:t];
    [leftV addSubview:gwcBtnl];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftV];
    
    UIView *leftV1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    UIButton *gwcBtn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    gwcBtn2.frame = CGRectMake(0, 5, 40, 30);
    gwcBtn2.userInteractionEnabled = NO;
    [gwcBtn2 setTitle:@"汇总" forState:UIControlStateNormal];
    gwcBtn2.titleLabel.font = [UIFont systemFontOfSize:15];
    [gwcBtn2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    UITapGestureRecognizer *t1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(rightAction:)];
    [leftV1 addGestureRecognizer:t1];
    [leftV1 addSubview:gwcBtn2];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftV1];
    
//    [self myTableView];
    [self requestRankingWithStartDate:nil endDate:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shenheAcrion:) name:@"shenhe" object:nil];
    
    UIView *bottomBGV = [[UIView alloc]initWithFrame:CGRectMake(0, SCREENHEIGHT-kTabBarHeight-20, SCREENWIDTH, kTabBarHeight+20)];
    bottomBGV.backgroundColor = RGBCOLOR(235, 235, 235);
    [self.view addSubview:bottomBGV];
    self.bottomBGV = bottomBGV;
    UIButton *lsddBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    lsddBtn.frame = CGRectMake(10, 15, bottomBGV.frame.size.width-20, 40);
    lsddBtn.backgroundColor = RGBCOLOR(108, 185, 252);
    lsddBtn.layer.cornerRadius = 5;
    [lsddBtn setTitle:@"订单详情" forState:UIControlStateNormal];
    [lsddBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [bottomBGV addSubview:lsddBtn];
    [lsddBtn addTarget:self action:@selector(lsddxqBtnAction:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)rightAction:(UIButton *)btn{
    SummaryOfUnauditedOrdersViewController *souoVC = [[SummaryOfUnauditedOrdersViewController alloc]init];
    souoVC.userData = self.userData;
    [self.navigationController pushViewController:souoVC animated:YES];
}
-(void)lsddxqBtnAction:(UIButton *)btn{
    if (self.dataDic) {
        //历史订单详情
        ReviewOrderDetailsViewController *ridVC = [[ReviewOrderDetailsViewController alloc]init];
        ridVC.dic = self.dataDic;
        ridVC.userData = self.userData;
        [self.navigationController pushViewController:ridVC animated:YES];
    }else{
        UIAlertView *a = [[UIAlertView alloc]initWithTitle:@"亲，请先选择订单哦！" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [a show];
    }
}
-(void)shenheAcrion:(NSNotificationCenter *)not{
    self.dataDicCellIndexPath = nil;
    self.dataDicCell = nil;
    self.dataDic = nil;
    [self requestRankingWithStartDate:nil endDate:nil];
}
-(void)leftAction:(UIButton *)btn{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)requestRankingWithStartDate:(NSString *)startDate endDate:(NSString *)endDate{
    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeClear];
    NSDictionary *dic = @{
        @"strDateS":@"",
        @"strDateE":@"",
        @"strReview":@"0"
    };
    NSString *str = [[NSUserDefaults standardUserDefaults] objectForKey:@"ipaddress"];
    if (str.length == 0) {
        // 请求头
//        NSString *accessPath = @"http://192.168.0.19:80/Api/OrderGoods/GetOrderInf";
        NSString *accessPath = @"http://crm.zhenyea.com/Api/OrderGoods/GetOrderInf";
        // 请求参数字典
        NSDictionary *params = @{
            @"strOrganizationNo":[NSString stringWithFormat:@"%@",self.userData[@"OrganizationNo"]],
//            @"strOrderID":[NSString stringWithFormat:@"%@",self.editDicccc[@"OrderID"]],
            @"strUserId":[NSString stringWithFormat:@"%@",self.userData[@"UserID"]],
            @"strPassword":[NSString stringWithFormat:@"%@",self.userData[@"UserPass"]],
            @"strIMEI":[FCUUID uuidForVendor],
            @"strDateS":@"",
            @"strDateE":@""
        };
        
        //创建配置信息
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        //设置请求超时时间：5秒
        configuration.timeoutIntervalForRequest = 5;
        //创建会话
        NSURLSession *session = [NSURLSession sessionWithConfiguration: configuration delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
        NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",accessPath]]];
        //设置请求方式：POST
        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/json" forHTTPHeaderField:@"content-Type"];
        [request setValue:@"application/json;charset=gb2312" forHTTPHeaderField:@"Accept"];
        
        //data的字典形式转化为data
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil];
        //设置请求体
        [request setHTTPBody:jsonData];
        
        NSURLSessionDataTask * dataTask =[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            [SVProgressHUD dismiss];
            if (error == nil) {
                NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
                NSString *receiveStr = [[NSString alloc]initWithData:data encoding:encoding];
                NSData * aData = [receiveStr dataUsingEncoding:NSUTF8StringEncoding];
                NSError *errorr = nil;
                id response = [NSJSONSerialization JSONObjectWithData:aData options:NSJSONReadingMutableContainers error:&errorr];
                if ([response isKindOfClass:[NSDictionary class]]) {
                    // 请求成功数据处理
                    NSString *IsResult = [NSString stringWithFormat:@"%@",[response objectForKey:@"IsResult"]];
                    if ([IsResult isEqualToString:@"1"]) {
                        // 请求成功数据处理
                        NSString *IsResult = [NSString stringWithFormat:@"%@",[response objectForKey:@"IsResult"]];
                        if ([IsResult isEqualToString:@"1"]) {
                            NSArray *a = response[@"Data"];
                            [self.myTableViewArr removeAllObjects];
                            [self.dataDDIC removeAllObjects];
                            for (int i=0; i<a.count; i++) {
                                ReviewOfTheOrderTableViewCellFrame *f = [[ReviewOfTheOrderTableViewCellFrame alloc]init];
                                f.dic = a[i];
                                [self.myTableViewArr addObject:f];
                                [self.dataDDIC addObject:a[i]];
                            }
                            [self.myTableView reloadData];
    
                            if (self.myTableViewArr.count == 0) {
                                self.noView.hidden = NO;
                                self.bottomBGV.hidden = YES;
                            }
                        }else{
                            [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                            [SVProgressHUD setMinimumDismissTimeInterval:0.2f];
                            [SVProgressHUD showImage:[UIImage imageNamed:@""] status:[NSString stringWithFormat:@"%@",response[@"Message"]]];
                        }
                    }else{
                        [SVProgressHUD setMinimumDismissTimeInterval:0.2f];
                        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:[NSString stringWithFormat:@"%@",response[@"Message"]]];
                    }
                } else {

                }
            }else{
                NSLog(@"error===%@",error);
            }
        }];
        [dataTask resume];

//        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//
//        NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:accessPath parameters:params error:nil];
//        request.timeoutInterval = 10.f;
//        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
//
//        NSURLSessionDataTask *task = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
//            [SVProgressHUD dismiss];
//            if (!error) {
//                if ([responseObject isKindOfClass:[NSDictionary class]]) {
//                    // 请求成功数据处理
//                    NSString *IsResult = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"IsResult"]];
//                    if ([IsResult isEqualToString:@"1"]) {
//                        NSArray *a = responseObject[@"Data"];
//                        [self.myTableViewArr removeAllObjects];
//                        [self.dataDDIC removeAllObjects];
//                        for (int i=0; i<a.count; i++) {
//                            ReviewOfTheOrderTableViewCellFrame *f = [[ReviewOfTheOrderTableViewCellFrame alloc]init];
//                            f.dic = a[i];
//                            [self.myTableViewArr addObject:f];
//                            [self.dataDDIC addObject:a[i]];
//                        }
//                        [self.myTableView reloadData];
//
//                        if (self.myTableViewArr.count == 0) {
//                            self.noView.hidden = NO;
//                            self.bottomBGV.hidden = YES;
//                        }
//                    }else{
//                        [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
//                        [SVProgressHUD setMinimumDismissTimeInterval:0.2f];
//                        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:[NSString stringWithFormat:@"%@",responseObject[@"Message"]]];
//                    }
//                } else {
//
//                }
//            } else {
//                NSData * data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
//                NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
//                NSLog(@"服务器的错误原因:%@",str);
//                [SVProgressHUD dismiss];
//            }
//        }];
//
//        [task resume];
    }else{
        [NetTools postWithUrl:[NSString stringWithFormat:@"http://%@/ldcy/OrderGoods/OrderGoods.asmx/GetOrderInf",str] pararms:dic
         success:^(id  _Nonnull json) {
            [SVProgressHUD dismiss];
            if ([[NSString stringWithFormat:@"%@",json[@"IsResult"]] isEqualToString:@"1"]) {
                NSArray *a = json[@"Data"];
                [self.myTableViewArr removeAllObjects];
                [self.dataDDIC removeAllObjects];
                for (int i=0; i<a.count; i++) {
                    ReviewOfTheOrderTableViewCellFrame *f = [[ReviewOfTheOrderTableViewCellFrame alloc]init];
                    f.dic = a[i];
                    [self.myTableViewArr addObject:f];
                    [self.dataDDIC addObject:a[i]];
                }
                [self.myTableView reloadData];
                
                if (self.myTableViewArr.count == 0) {
                    self.noView.hidden = NO;
                    self.bottomBGV.hidden = YES;
                }
            }else{
                [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                [SVProgressHUD setMinimumDismissTimeInterval:0.2f];
                [SVProgressHUD showImage:[UIImage imageNamed:@""] status:[NSString stringWithFormat:@"%@",json[@"Message"]]];
            }
        } fail:^(NSError * _Nonnull error) {
            NSData * data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
            NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"服务器的错误原因:%@",str);
            [SVProgressHUD dismiss];
        }];
    }
    
}
@end
